package v1

import (
	"gitee.com/buddyxiao/ginblog/model"
	"gitee.com/buddyxiao/ginblog/utils"
	"gitee.com/buddyxiao/ginblog/utils/errmsg"
	"gitee.com/buddyxiao/ginblog/utils/validator"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// AddUser 添加用户
func AddUser(ctx *gin.Context) {
	var data model.User
	_ = ctx.ShouldBindJSON(&data)
	// 数据验证
	msg, code := validator.Validate(&data)
	if code != errmsg.SUCCESS {
		ctx.JSON(http.StatusOK, gin.H{
			"status": code,
			"msg":    msg,
		})
		return
	}
	code = model.CheckUser(data.Username)
	if code == errmsg.SUCCESS {
		model.CreateUser(&data)
	}
	if code == errmsg.ERROR_USERNAME_USED {
		code = errmsg.ERROR_USERNAME_USED
	}
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// 查询单个用户
func GetUserInfo(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	user, code := model.GetUser(id)
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   user,
		"total":  1,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// GetUsers 查询用户列表
func GetUsers(ctx *gin.Context) {
	pageNum, _ := strconv.Atoi(ctx.Query("pageNum"))
	pageSize, _ := strconv.Atoi(ctx.Query("pageSize"))
	username := ctx.DefaultQuery("username", "")
	// 页码预处理
	utils.CheckPage(&pageNum, &pageSize)
	data, err, total := model.GetUsers(username, pageNum, pageSize)
	code := errmsg.SUCCESS
	if err != nil {
		code = errmsg.ERROR
	}
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"total":  total,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// EditUser 编辑用户
func EditUser(ctx *gin.Context) {
	var data model.User
	id, _ := strconv.Atoi(ctx.Param("id"))
	_ = ctx.ShouldBindJSON(&data)
	code := model.CheckUpUser(id, data.Username)
	if code == errmsg.ERROR_USERNAME_USED {
		ctx.Abort()
	} else { // 用户名不存在
		model.EditUser(id, &data)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// DeleteUser 删除用户
func DeleteUser(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	code := model.DeleteUser(id)
	ctx.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    errmsg.GetErrMsg(code),
	})

}
